package club.itstudio.itouc.controller.admin
//
//import club.itstudio.itouc.config.AdminConfig
//import club.itstudio.itouc.core.exception.ITOUCException
//import club.itstudio.itouc.core.util.*
//import club.itstudio.itouc.service.EmailService
//import club.itstudio.itouc.util.Redis
//import org.hibernate.validator.constraints.Length
//import org.springframework.scheduling.annotation.Scheduled
//import org.springframework.web.bind.annotation.*
//import javax.servlet.http.Cookie
//import javax.servlet.http.HttpServletResponse
//import javax.validation.constraints.Email
//import kotlin.random.Random
//
//@RestController
//@RequestMapping("/admin")
//class AdminLogin(val resource: Resource,
//                 val emailService: EmailService,
//                 val adminConfig: AdminConfig,
//                 val redis: Redis) {
//
//
//    val captchaMap = mutableMapOf<String, EmailCaptcha>()
//    /**
//     * 管理员登录界面
//     */
//    @GetMapping("/login")
//    fun loginPage(): String {
//        return resource.template("admin/login.html")
//    }
//
//    /**
//     * 发送验证码
//     */
//    @GetMapping("/login/captcha")
//    fun sendCaptcha(@Length(max = 30) @Email @RequestParam email: String): Result<Any> {
//        if (adminConfig.contains(email)) {
//            val captcha = Random.nextIntStr(6)
//            val data = EmailCaptcha(email, captcha, System.currentTimeMillis() + 5 * 60 * 1000)
//            captchaMap[email] = data
//            emailService.sendCaptcha(captcha, email)
//            return ResultUtil.success()
//        }
//        return ResultUtil.error("邮箱无效")
//    }
//
//    /**
//     * 获取adminToken
//     * @param email: 邮箱
//     * @param captcha: 验证码
//     */
//    @PostMapping("/login")
//    fun adminLogin(@Length(max = 30) @Email @RequestParam email: String,
//                   @Length(max = 6) @RequestParam captcha: String,
//                   response: HttpServletResponse): Result<Any> {
//        if (captchaMap.containsKey(email)) {
//            val data = captchaMap[email]  ?: throw ITOUCException()
//            val now = System.currentTimeMillis()
//            if (data.captcha == captcha && data.expire >= now) {
//                val adminToken = Random.nextStr(28)
//                val cookie = Cookie("adminToken", adminToken)
//                cookie.path = "/"
//                // 20分钟过期
//                cookie.maxAge = 1200
//                response.addCookie(cookie)
//                redis.saveAdminLoginToken(adminToken)
//                return ResultUtil.success()
//            }
//        }
//        return ResultUtil.error()
//    }
//
//    // 定时清理验证码
//    @Scheduled(cron = "0 0 3 * * ? ")
//    fun clearCaptcha() {
//        captchaMap.clear()
//    }
//
//    // 邮件验证码
//    data class EmailCaptcha(
//            val email: String,
//            val captcha: String,
//            val expire: Long
//    )
//
//}